package cn.edu.ldu.protocol;

import cn.edu.ldu.modules.controller.*;
import cn.edu.ldu.modules.entity.*;
import cn.edu.ldu.util.Util;
import cn.edu.ldu.views.ServerView;
import cn.edu.ldu.views.modules.controller.UserController;
import cn.edu.ldu.views.modules.controller.UserIpController;
import cn.edu.ldu.views.modules.entity.UserIpEntity;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import cn.edu.ldu.views.modules.controller.ServerViewController;
import cn.edu.ldu.util.Consts;
import cn.edu.ldu.util.R;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class Login {
    private ServerView view;

    public Login(Protocol protocol) throws Exception {
        view = ServerViewController.getServerView();
        userLogin(protocol);
    }

    /**
     * 判断登录，登录成功则返回好友列表和待办信息
     * @param protocol
     * @throws Exception
     */
    private void userLogin(Protocol protocol) throws Exception {
        //获取数据库信息,转换为实体对象
//        UserEntity loginUser = JSON.parseObject(protocol.getData(), UserEntity.class);
        UserEntity user = JSON.parseObject(protocol.getData(), UserEntity.class);
        String token = null;
        try {
            token = LoginController.login(user);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if(token == null){
            Protocol p = protocol;
            p.setKey(Consts.P_LOGIN_FAILURE);
            p.setData(null);
            UserController.sendMsgToUser(p);
        }else {
//            AppUserController.sendMsgToUser(cn.edu.ldu.protocol.getPacket(), Consts.M_SUCCESS);
            user = AppUserController.getUser(user.getId(), token);
            if(user == null)
                return;

            TokenEntity tokenEntity = new TokenEntity();
            tokenEntity.setUserId(user.getId());
            tokenEntity.setToken(token);
            tokenEntity.setPort(protocol.getPacket().getPort());
            tokenEntity.setAddress(protocol.getPacket().getAddress());

//            String nowIpInfo = updateLoginInfo(user.getId(), protocol);

            //更新服务器界面

            if(UserController.getUserList().get(user.getId()) != null){
                UserController.removeUserToList(user.getId());
                view.consoleJTA(user.getId() + " : 下线了！\n");
                ServerViewController.getServerView().offlineListJTA(String.valueOf(user.getId()));
            }else
                view.onlineListJTA(user.getId() + " \n");

            view.consoleJTA(user.getId() + " : 上线了！\n");
            view.updateTable(new String[]{"",
                    String.valueOf(user.getId()),
//                    new StringBuffer(protocol.getPacket().getAddress().toString()).replace(0, 1, "").append(" (").append(Util.getIpInfo(protocol.getPacket().getAddress()).getCity()).append(")").toString(),
                    new StringBuffer(protocol.getPacket().getAddress().toString()).replace(0, 1, "").toString(),
                    ""
            });

            UserController.addUserToList(tokenEntity);

            //获取好友在线列表
            List<FriendsEntity> allFriends = new ArrayList<>();
            List<FriendsEntity> onlineFriends = new ArrayList<>();
            List<FriendsEntity> offlineFriends = new ArrayList<>();
            try {
                allFriends = FriendsController.getFriendsByUserId(user.getId(), token);
                if(allFriends != null){
                    for(FriendsEntity fe : allFriends){
                        if(UserController.getUserList().containsKey(fe.getFriendId())){
                            onlineFriends.add(fe);
                        }else {
                            offlineFriends.add(fe);
                        }
                    }
                }

                //获取个人信息
                UserAccountEntity accountEntity = UserAccountController.getUserAccount(user.getId(), token);

                //获取代办信息
                List<ChatHistoryEntity> withoutHandleCH = ChatHistoryController.getWithoutHandleMsg(user.getId(), 0, token);
                List<FriendsEntity> withoutHandleFE = FriendsController.getWithoutHandleMsg(user.getId(), 0, token);

                //获取群聊信息
                List<GroupChatEntity> groupChatEntities = GroupChatController.getGroupChats(user.getId(), token);

                R r = new R();
                r.put(Consts.K_ACCOUNT_INFO, accountEntity);
                r.put(Consts.K_GROUP_CHAT, groupChatEntities);
                r.put(Consts.K_TODO_CHAT_FRIEND, withoutHandleCH);
                r.put(Consts.K_TODO_FRIEND_FRIEND, withoutHandleFE);
                r.put(Consts.K_USER_INFO, user);
                r.put(Consts.K_ONLINE_FRIEND, onlineFriends);
                r.put(Consts.K_OFFLINE_FRIEND, offlineFriends);
                r.put(Consts.K_TOKEN, token);

                Protocol pro = new Protocol();
                pro.setKey(Consts.P_LOGIN_SUCCESS);
                pro.setData(JSONObject.toJSONString(r));

                UserController.sendDataToUser(user.getId(), pro);


                //通知所有在线好友：“我上线了”
                for(FriendsEntity of : onlineFriends){
                    Protocol p = new Protocol();
                    FriendsEntity fe = FriendsController.getFriendByUserId(of.getFriendId(), of.getUserId(), token);
                    p.setData(JSONObject.toJSONString(fe));
                    p.setKey("FriendOnline");
                    UserController.sendDataToUser(of.getFriendId(), p);

                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private String updateLoginInfo(Long userId, Protocol protocol) throws Exception {

        UserIpEntity lastIp = UserIpController.getUserLastIp(userId, protocol.getToken());

        UserIpEntity nowIp = Util.getIpInfo(protocol.getPacket().getAddress());
        if(nowIp != null){
            nowIp.setUserId(userId);
            nowIp.setCreateTime(Calendar.getInstance().getTime());
            if(lastIp != null && lastIp.getCity().equals(nowIp.getCity())){
                view.consoleJTA("异地登录");
            }
            UserIpController.addUserIp(nowIp, protocol.getToken());
            return nowIp.getIp() + " (" + nowIp.getCity() + ")";
        }

        return null;
    }

}
